package com.vdg.fps;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.vdg.R;
import com.vdg.fps.adapter.ListFriendsAdapter;
import com.vdg.fps.adapter.ListGroupsAdapter;
import com.vdg.fps.adapter.ListLikedPagesAdapter;
import com.vdg.fps.config.FPSConfig;
import com.vdg.fps.data.FaceBookAccount;
import com.vdg.fps.data.GroupsData;
import com.vdg.fps.listener.OnRequestListnener;
import com.vdg.fps.services.FPSService;
import com.vdg.fps.services.FPSService.LocalBinder;
import com.vdg.fps.ui.view.TextViewPlus;
import com.vdg.fps.ulti.Utilities;
import com.vdg.ui.fragment.AccountsFragment;

public class FetchLikedPagesListActivity extends BaseActivity {
	private FaceBookAccount mFaceBookAccount;
	private int mAccountIndex;
	private FPSService mService;
	private TextViewPlus mTxvFetchGroups;
	private ArrayList<GroupsData> mGroupsDatas;
	private ListLikedPagesAdapter mListLikedPagesAdapter;
	private TextViewPlus mTxvExportAll;
	private ListView mListView;
	private FrameLayout mFrmLoadingDialog;
	private EditText mEdtSearch;
	private GroupsData mSelectData;
	public static String GROUP_KEY = "group_key";
	private TextViewPlus mTxvTitle;

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// TODO Auto-generated method stub
		super.onServiceConnected(name, service);
		LocalBinder binder = (LocalBinder) service;
		mService = binder.getService();
		init();
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		super.onServiceDisconnected(name);
		mService = null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fetch_liked_layout);
	}

	private void init() {
		mGroupsDatas = new ArrayList<GroupsData>();
		mListView = (ListView) findViewById(R.id.liv_liked_pages);
		mListLikedPagesAdapter = new ListLikedPagesAdapter(this, 0,
				mGroupsDatas);
		mListView.setAdapter(mListLikedPagesAdapter);
		mListView.setStackFromBottom(false);
		mTxvTitle = (TextViewPlus) findViewById(R.id.txv_title);
		mTxvFetchGroups = (TextViewPlus) findViewById(R.id.txv_fecth_pages);
		mTxvExportAll = (TextViewPlus) findViewById(R.id.txv_export_all);
		mFrmLoadingDialog = (FrameLayout) findViewById(R.id.frm_loading_dialog);
		mEdtSearch = (EditText) findViewById(R.id.edt_search);
		mEdtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (mListLikedPagesAdapter != null) {
					mListLikedPagesAdapter.filter(s.toString());
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		mTxvExportAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mGroupsDatas != null && mGroupsDatas.size() > 0)
					Utilities.startSaveFile(
							FPSConfig.LIKED_PAGES_FOLDER,
							mFaceBookAccount.getUserName()
									+ "_all_liked_pages.txt",
							FetchLikedPagesListActivity.this,
							GroupsData.toString(
									mListLikedPagesAdapter.getDisplayData())
									.getBytes());
			}
		});

		mTxvFetchGroups.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mService != null && mFaceBookAccount != null) {
					mFrmLoadingDialog.setVisibility(View.VISIBLE);
					mService.FetchLikedPages(mFaceBookAccount,
							new OnRequestListnener() {

								@Override
								public void onSuccess(String response) {
									Log.v("debug", "jsonArray null2222222");
									// TODO Auto-generated method stub
									JSONObject root;
									try {
										root = new JSONObject(response);
									} catch (JSONException e2) {
										// TODO Auto-generated catch block
										e2.printStackTrace();
										Utilities.showToast(
												e2.getMessage(),
												FetchLikedPagesListActivity.this);
										mFrmLoadingDialog
												.setVisibility(View.GONE);
										return;
									}
									JSONArray jsonArray = null;
									try {
										jsonArray = new JSONArray(root
												.getString("data"));
									} catch (JSONException e1) {
										// TODO Auto-generated catch block
										Utilities.showToast(
												e1.getMessage(),
												FetchLikedPagesListActivity.this);
										e1.printStackTrace();
										mFrmLoadingDialog
												.setVisibility(View.GONE);
										return;
									}
									if (jsonArray == null
											&& jsonArray.length() == 0) {
										Log.v("debug", "jsonArray null");
										return;
									}
									mGroupsDatas.clear();
									for (int i = 0; i < jsonArray.length(); i++) {
										try {
											JSONObject object = jsonArray
													.getJSONObject(i);
											if (object != null) {
												String id = object
														.getString("id");
												String name = object
														.getString("name");
												String likes = object
														.getString("likes");
												boolean canpost = false;
												if (!object.isNull("can_post")) {
													canpost = Boolean.valueOf(object
															.getString("can_post"));
												}

												Log.v("debug1", " " + canpost);
												String category = object
														.getString("category");
												mGroupsDatas
														.add(new GroupsData(id,
																name, canpost,
																likes, category));
											}
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											// Utilities.showToast(
											// e.getMessage(),
											// FetchGroupsListActivity.this);
											e.printStackTrace();
											mFrmLoadingDialog
													.setVisibility(View.GONE);
											// return;
										}
									}
									mFrmLoadingDialog.setVisibility(View.GONE);
									mListLikedPagesAdapter = new ListLikedPagesAdapter(
											FetchLikedPagesListActivity.this,
											0, mGroupsDatas);
									mListView
											.setAdapter(mListLikedPagesAdapter);
									mListLikedPagesAdapter
											.notifyDataSetChanged();
									if (mGroupsDatas.size() > 0)
										mListView.setSelection(0);
									mTxvTitle.setText("Your Liked Pages " + "("
											+ mGroupsDatas.size() + ")");
								}

								@Override
								public void onFailed(int errorCode) {
									// TODO Auto-generated method stub
									Utilities.showError(errorCode,
											FetchLikedPagesListActivity.this);
									mFrmLoadingDialog.setVisibility(View.GONE);
								}
							});
				}
			}
		});
		Intent intent = getIntent();
		if (intent != null) {
			mAccountIndex = (Integer) intent.getIntExtra(
					AccountsFragment.FACE_BOOK_ACCOUNT_KEY, -1);
		}
		if (mAccountIndex != -1) {
			if (mService.getFacebookAccount(mAccountIndex) != null) {
				mFaceBookAccount = mService.getFacebookAccount(mAccountIndex);
			}
		}
		setUIFont();
		registerForContextMenu(mListView);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				mSelectData = mListLikedPagesAdapter.getItem(position);
				openContextMenu(mListView);
				// registerForContextMenu(mListView);
				// openContextMenu(view);
				// unregisterForContextMenu(view);
			}
		});
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				mSelectData = mListLikedPagesAdapter.getItem(position);
				return false;
			}

		});
	}

	private void setUIFont() {
		Typeface type = Typeface
				.createFromAsset(getAssets(), FPSConfig.UI_FONT);
		mEdtSearch.setTypeface(type);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		menu.setHeaderTitle("Menu");
		menu.add(0, v.getId(), 1, "View this profile on browser");
		menu.add(0, v.getId(), 1, "Copy ID");
		menu.add(0, v.getId(), 1, "Copy Name");
		menu.add(0, v.getId(), 1, "Export selected IDs to clipboard");
		menu.add(0, v.getId(), 1, "Export all IDs to clipboard");
		menu.add(0, v.getId(), 1, "Export selected IDs to sdCard");
		menu.add(0, v.getId(), 1, "Export all IDs to sdCard");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getTitle().equals("View this profile on browser")) {
			Intent browserIntent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("https://m.facebook.com/" + mSelectData.getID()));
			startActivity(browserIntent);
		}
		if (item.getTitle().equals("Copy ID")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(mSelectData.getID());
			Utilities.showToast("Coppy ID to clipboard sucessfully!",
					FetchLikedPagesListActivity.this);
		}
		if (item.getTitle().equals("Copy Name")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(mSelectData.getName());
			Utilities.showToast("Coppy Name to clipboard sucessfully!",
					FetchLikedPagesListActivity.this);
		}
		if (item.getTitle().equals("Export selected IDs to clipboard")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(mSelectData.toString());
			Utilities.showToast("Coppy selected IDs to clipboard sucessfully!",
					FetchLikedPagesListActivity.this);
		}
		if (item.getTitle().equals("Export all IDs to clipboard")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(GroupsData.toString(mListLikedPagesAdapter
					.getDisplayData()));
			Utilities.showToast("Coppy all IDs to clipboard sucessfully!",
					FetchLikedPagesListActivity.this);
		}
		if (item.getTitle().equals("Export selected IDs to sdCard")) {
			Utilities.startSaveFile(FPSConfig.LIKED_PAGES_FOLDER,
					mSelectData.getName() + ".txt",
					FetchLikedPagesListActivity.this, mSelectData.toString()
							.getBytes());
		}
		if (item.getTitle().equals("Export all IDs to sdCard")) {
			Utilities.startSaveFile(FPSConfig.LIKED_PAGES_FOLDER,
					mFaceBookAccount.getUserName() + "_all_liked_pages.txt",
					FetchLikedPagesListActivity.this,
					GroupsData
							.toString(mListLikedPagesAdapter.getDisplayData())
							.getBytes());
		}
		closeContextMenu();
		return super.onContextItemSelected(item);
	}
}
